<template>
  <el-dialog
      v-model=visible
      :title = "!dataForm.ID?'新增':'修改'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
  >
    <el-form ref="formRef" :model="dataForm" :rules="dataRule" label-width="80px" @keyup.enter = "dataFormSubmit()">
      <el-form-item label="人物ID" prop="People">
        <el-input v-model="dataForm.People" placeholder="人物ID" />
      </el-form-item>
      <el-form-item label="事件标题" prop="Title">
        <el-input v-model="dataForm.Title" placeholder="事件标题" />
      </el-form-item>
      <el-form-item label="发生时间" prop="EventTime">
        <el-input v-model="dataForm.EventTime" placeholder="发生时间" />
      </el-form-item>
      <el-form-item label="事迹内容" prop="Content">
        <el-input v-model="dataForm.Content" :rows="5" type="textarea" placeholder="事迹内容" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="dataFormSubmit">确定</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {nextTick, reactive, ref} from "vue";
import request from '../../utils/request'
import {ElMessage} from "element-plus";
const emit = defineEmits(['refreshDataList'])

const formRef = ref()
let visible = ref(false)
const dataForm = reactive({
  ID:'',
  People:'',
  Title: '',
  EventTime:'',
  Content:''
})
const dataRule = reactive({
  Name:[]
})

const resetForm = () =>{
  formRef.value.resetFields()
}

const init = (id)=>{
  dataForm.ID = id || 0
  visible.value = true
  nextTick(()=>{
    resetForm()
    if(dataForm.ID){
      request.get(`/event/details/${id}`).then((data)=>{
        if (data && data.code === 0){
          dataForm.ID = data.data.ID
          dataForm.People = data.data.People
          dataForm.Title = data.data.Title
          dataForm.EventTime = data.data.EventTime
          dataForm.Content = data.data.Content
        }
      })
    }
  })
}

const dataFormSubmit = ()=>{
  request.post(`/event/${!dataForm.ID ? 'create':'update'}`,{
    ID:dataForm.ID,
    People:dataForm.People,
    Title: dataForm.Title,
    EventTime:dataForm.EventTime,
    Content:dataForm.Content
  }).then((data) =>{
    if (data && data.code === 0){
      ElMessage({
        message:"操作成功",
        type:"success",
        duration:1500,
        onClose:() =>{
          visible.value = false
          emit('refreshDataList')
        }
      })
    }else {
      ElMessage.error(data.message)
    }
  })
}
defineExpose({
  init
})

</script>

<style scoped>

</style>
